package SERVLET;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import BO.UsuarioBO;
import DTO.UsuarioDTO;

public class UsuarioServlet extends HttpServlet {
    
    private UsuarioBO usuarioBO = new UsuarioBO();
    private UsuarioDTO usuarioDTO = new UsuarioDTO();    
    private boolean incluindo;
    private boolean alterando;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Cache-control", "no-cache, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "Fri, 25 Dec 1980 00:00:00 GMT");

        if (request.getParameter("acao") != null) {
        	if (request.getParameter("acao").equals("Novo Usuario")) {
                novo(request, response);
            } else if (request.getParameter("acao").equals("Editar")) {
                editar(request, response);
            } else if (request.getParameter("acao").equals("Excluir")) {
                excluir(request, response);
            } else if (request.getParameter("acao").equals("Pesquisar")){
            	pesquisar(request, response);
            } else if (request.getParameter("acao").equals("Incluir")) {
                incluir(request, response);                   
            } else {
                redicionarPesquisarRemoverAtributo(request, response);
            }
        }
    }
       
    private void novo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    	usuarioDTO = new UsuarioDTO();
        request.getSession().setAttribute("usuarioDTO", usuarioDTO);
        setIncluindo(true);
        setAlterando(false);
        redicionarIncluirAlterarRemoverAtributo(request, response);
    }        
    
    private void pesquisar(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    	usuarioDTO.setLogin(request.getParameter("pesquisa"));
        request.getSession().setAttribute("usuarios", usuarioBO.pesquisarPorLogin(usuarioDTO));
        redicionarPesquisar(request, response);
    }
    
    private void editar(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    	usuarioDTO.setCodigo(Long.parseLong(request.getParameter("id")));
        usuarioDTO = usuarioBO.pesquisarPorCodigo(usuarioDTO.getCodigo());
        request.getSession().setAttribute("usuarioDTO", usuarioDTO);
        setAlterando(true);
        setIncluindo(false);
        redicionarIncluirAlterarRemoverAtributo(request, response);
    }        
    
    private void excluir(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    	usuarioDTO.setCodigo(Long.parseLong(request.getParameter("id")));
        usuarioDTO = usuarioBO.pesquisarPorCodigo(usuarioDTO.getCodigo());
        if (!usuarioBO.remover(usuarioDTO)) {
            request.getSession().setAttribute("erro", "Erro ao realizar exclusão.");
            redicionarPesquisar(request, response);
        } else {
        	request.getSession().setAttribute("usuarios", usuarioBO.pesquisarTodos());
        	redicionarIncluirAlterarRemoverAtributo(request, response);
        }               
    }    
    
    private void incluir(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    	String oldOne = usuarioDTO.getLogin();
        criarObjeto(request);                
        if (!usuarioBO.existe(usuarioDTO) || (isAlterando() && usuarioDTO.getLogin().equals(oldOne))) {
            if (isIncluindo() ? usuarioBO.incluir(usuarioDTO) : isAlterando() ? usuarioBO.alterar(usuarioDTO) : false) {                        
                alterando = incluindo = false;
                request.getSession().setAttribute("usuarios", usuarioBO.pesquisarTodos());
                redicionarPesquisarRemoverAtributo(request, response);
            }
        } else {
            usuarioDTO.setLogin(oldOne);
            request.getSession().setAttribute("erro", "Usuario já existe.");
            redicionarIncluirAlterar(request, response);
        }             
    }
    
    private void redicionarPesquisarRemoverAtributo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        request.getSession().removeAttribute("erro");
        redicionarPesquisar(request, response);
    }
       
    private void redicionarIncluirAlterarRemoverAtributo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        removerAtributo(request);
        redicionarIncluirAlterar(request, response);
    }
    
    private void removerAtributo(HttpServletRequest request){
        request.getSession().removeAttribute("erro");
    }
    
    private void redicionarPesquisar(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{    	
        request.getRequestDispatcher(HomeServlet.paginas.get("usuarioPesquisar")).forward(request, response);
    }
    
    private void redicionarIncluirAlterar(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{    	
        request.getRequestDispatcher(HomeServlet.paginas.get("usuarioIncluirAlterar")).forward(request, response);
    }
    
    private void criarObjeto(HttpServletRequest request) {    	        
        usuarioDTO.setLogin(request.getParameter("login"));
        usuarioDTO.setSenha(request.getParameter("senha"));
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }
       
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }

    public boolean isIncluindo() {
        return incluindo;
    }

    public void setIncluindo(boolean incluindo) {
        this.incluindo = incluindo;
    }

    public boolean isAlterando() {
        return alterando;
    }

    public void setAlterando(boolean alterando) {
        this.alterando = alterando;
    } 
}